<template>
  <div class="cashier-container">
    <!-- 顶部导航 -->
    <div class="cashier-header">
      <h2>智教商城收银台</h2>
    </div>

    <!-- 倒计时提示 -->
    <div class="countdown-banner">
      <div class="countdown-content">
        <div class="success-icon">
          <CheckCircleOutlined />
        </div>
        <div class="countdown-text">
          <p>订单提交成功，请尽快付款！订单号：{{ orderInfo.orderNo }}</p>
          <p>请您在 <span class="countdown">{{ countdownText }}</span> 内完成支付，否则订单会被自动取消</p>
        </div>
      </div>
    </div>

    <!-- 支付金额 -->
    <div class="payment-amount">
      <div class="amount-label">应付金额</div>
      <div class="amount-value">¥{{ orderInfo.totalAmount.toFixed(2)}}</div>
      <a-button type="link" @click="showOrderDetail = !showOrderDetail">
        {{ showOrderDetail ? '隐藏' : '显示' }}订单详情
      </a-button>
    </div>

    <!-- 订单详情 -->
    <div v-if="showOrderDetail" class="order-detail">
      <!-- 单个商品时的显示方式 -->
      <div v-if="orderInfo.products.length === 1" class="single-product">
        <div class="detail-item">
          <span class="label">商品名称：</span>
          <span class="value">{{ orderInfo.products[0].productName }}</span>
        </div>
        <div class="detail-item">
          <span class="label">商品单价：</span>
          <span class="value">¥{{ orderInfo.products[0].price.toFixed(2)/orderInfo.products[0].quantity }}</span>
        </div>
        <div class="detail-item">
          <span class="label">购买数量：</span>
          <span class="value">{{ orderInfo.products[0].quantity }}</span>
        </div>
      </div>
      
      <!-- 多个商品时的显示方式 -->
      <div v-else class="multiple-products">
        <div class="products-header">
          <h4>商品清单</h4>
          <span>共 {{ orderInfo.products.length }} 件商品</span>
        </div>
        <div class="product-list">
          <div v-for="(product, index) in orderInfo.products" :key="index" class="product-item">
            <img :src="product.mainImage" :alt="product.productName" class="product-thumb" />
            <div class="product-info">
              <div class="product-name">{{ product.productName }}</div>
              <div class="product-price-quantity">
                <span class="price">¥{{ product.price.toFixed(2) }}</span>
                <span class="quantity">x{{ product.quantity }}</span>
              </div>
            </div>
            <div class="product-total">
              ¥{{ (product.price * product.quantity).toFixed(2) }}
            </div>
          </div>
        </div>
      </div>
      
      <div class="detail-item">
        <span class="label">订单时间：</span>
        <span class="value">{{ orderInfo.createTime }}</span>
      </div>
    </div>

    <!-- 支付方式 -->
    <div class="payment-methods">
      <h3 class="section-title">支付方式</h3>
      
      <div class="method-list">
        <div class="method-item" :class="{ active: selectedMethod === 'alipay' }" @click="selectedMethod = 'alipay'">
          <div class="method-icon">
            <!-- <img src="@/assets/alipay-logo.png" alt="支付宝"> -->
          </div>
          <div class="method-info">
            <div class="method-name">支付宝</div>
            <div class="method-desc">推荐已安装支付宝客户端的用户使用</div>
          </div>
          <div class="method-select">
            <CheckOutlined v-if="selectedMethod === 'alipay'" />
          </div>
        </div>

        <div class="method-item" :class="{ active: selectedMethod === 'wechat' }" @click="selectedMethod = 'wechat'">
          <div class="method-icon">
            <!-- <img src="@/assets/wechatpay-logo.png" alt="微信支付"> -->
          </div>
          <div class="method-info">
            <div class="method-name">微信支付</div>
            <div class="method-desc">推荐微信用户使用</div>
          </div>
          <div class="method-select">
            <CheckOutlined v-if="selectedMethod === 'wechat'" />
          </div>
        </div>
      </div>
    </div>

    <!-- 支付按钮 -->
    <div class="payment-action">
      <a-button 
        type="primary" 
        size="large" 
        class="pay-button"
        @click="handlePayment"
        :loading="isPaying"
      >
        立即支付 ¥{{ orderInfo.totalAmount.toFixed(2) }}
      </a-button>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted, onUnmounted } from 'vue'
import { useRouter } from 'vue-router'
import { CheckCircleOutlined, CheckOutlined } from '@ant-design/icons-vue'
import { message } from 'ant-design-vue'
import { createOrder1 } from '@/api/mall/alipayController'

const router = useRouter()

// 订单信息 - 修改为支持多个商品
const orderInfo = ref({
  orderNo: '',
  products: [] as Array<{
    productId: number
    productName: string
    price: number
    quantity: number
    mainImage: string
  }>,
  totalAmount: 0,
  createTime: new Date().toLocaleString()
})

// 支付方式
const selectedMethod = ref('alipay')
const isPaying = ref(false)
const showOrderDetail = ref(false)

// 倒计时相关
const countdown = ref(24 * 60 * 60) // 24小时，单位秒
let timer: number | null = null

// 格式化倒计时文本
const countdownText = computed(() => {
  const hours = Math.floor(countdown.value / 3600)
  const minutes = Math.floor((countdown.value % 3600) / 60)
  const seconds = countdown.value % 60
  return `${hours}时${minutes}分${seconds}秒`
})

// 修改初始化逻辑以支持多个商品
const initOrderInfo = () => {
  const route = router.currentRoute.value
  const { orderNo } = route.query
  
  // 从sessionStorage恢复订单
  const savedOrder = sessionStorage.getItem('currentOrder')
  if (!savedOrder) {
    message.error('订单信息已丢失，请重新下单')
    router.push('/')
    return
  }
  
  const orderData = JSON.parse(savedOrder)
  
  // 验证订单号匹配
  if (orderNo !== orderData.orderNo) {
    message.error('订单信息不匹配')
    router.push('/')
    return
  }
  
  // 验证订单时间（30分钟内有效）
  const THIRTY_MINUTES = 30 * 60 * 1000
  if (Date.now() - orderData.createdAt > THIRTY_MINUTES) {
    message.error('订单已过期，请重新下单')
    router.push('/')
    return
  }
  
  // 兼容旧数据结构（单个商品）和新数据结构（多个商品）
  if (orderData.products && Array.isArray(orderData.products)) {
    // 新数据结构：多个商品
    orderInfo.value = {
      orderNo: orderData.orderNo,
      products: orderData.products,
      totalAmount: orderData.totalAmount,
      createTime: new Date(orderData.createdAt).toLocaleString()
    }
  } else {
    // 旧数据结构：单个商品（从DetailShop.vue传来的）
    orderInfo.value = {
      orderNo: orderData.orderNo,
      products: [{
        productId: orderData.product.productId,
        productName: orderData.product.productName,
        price: orderData.product.price,
        quantity: orderData.quantity,
        mainImage: orderData.product.mainImage
      }],
      totalAmount: orderData.product.price ,
      createTime: new Date(orderData.createdAt).toLocaleString()
    }
  }
}

// 处理支付
const handlePayment = async () => {
  isPaying.value = true
  
  try {
    if (selectedMethod.value === 'alipay') {
      // 为多个商品创建描述
      const subject = orderInfo.value.products.length > 1 
        ? `购买${orderInfo.value.products.length}件商品` 
        : orderInfo.value.products[0].productName
      
      const params = {
        orderNo: orderInfo.value.orderNo,
        amount: orderInfo.value.totalAmount.toFixed(2),
        subject
      }
      
      const res = await createOrder1(params)
      
      // 支付宝支付需要跳转到支付页面
      const payWindow = window.open('', '_blank')
      if (payWindow) {
        payWindow.document.write(res)
        payWindow.document.close()
      } else {
        throw new Error('无法打开支付窗口，请检查浏览器弹窗设置')
      }
    } else {
      // 微信支付逻辑
      message.success('微信支付功能开发中')
    }
    sessionStorage.removeItem('currentOrder')
  } catch (error) {
    console.error('支付失败:', error)
    message.error(`支付失败: ${error instanceof Error ? error.message : '未知错误'}`)
  } finally {
    isPaying.value = false
  }
}

// 初始化倒计时
const initCountdown = () => {
  timer = window.setInterval(() => {
    if (countdown.value > 0) {
      countdown.value -= 1
    } else {
      clearInterval(timer as number)
      message.warning('订单已超时，请重新下单')
      router.push('/')
    }
  }, 1000)
}

// 添加beforeUnload事件监听
onMounted(() => {
  initOrderInfo()
  initCountdown()
  
  window.addEventListener('beforeunload', handleBeforeUnload)
})

onUnmounted(() => {
  if (timer) clearInterval(timer)
  window.removeEventListener('beforeunload', handleBeforeUnload)
})

const handleBeforeUnload = (e: BeforeUnloadEvent) => {
  // 可以在这里添加提示
  // e.preventDefault()
  // return (e.returnValue = '确定要离开吗？未完成的订单可能会丢失')
}
</script>

<style scoped>
/* 添加多商品展示样式 */
.multiple-products {
  margin-bottom: 15px;
}

.products-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 10px;
  padding-bottom: 10px;
  border-bottom: 1px solid #f0f0f0;
}

.products-header h4 {
  margin: 0;
  font-size: 16px;
}

.product-list {
  max-height: 300px;
  overflow-y: auto;
}

.product-item {
  display: flex;
  align-items: center;
  padding: 10px 0;
  border-bottom: 1px solid #f5f5f5;
}

.product-item:last-child {
  border-bottom: none;
}

.product-thumb {
  width: 50px;
  height: 50px;
  object-fit: cover;
  border-radius: 4px;
  margin-right: 10px;
}

.product-info {
  flex: 1;
}

.product-name {
  font-size: 14px;
  margin-bottom: 5px;
  line-height: 1.3;
}

.product-price-quantity {
  display: flex;
  justify-content: space-between;
  font-size: 12px;
  color: #999;
}

.product-total {
  font-weight: bold;
  color: #f5222d;
  margin-left: 10px;
}

/* 其他样式保持不变 */
.cashier-container {
  max-width: 800px;
  margin: 0 auto;
  padding: 20px;
  background-color: #fff;
  min-height: 100vh;
}

.cashier-header {
  text-align: center;
  margin-bottom: 30px;
  padding-bottom: 20px;
  border-bottom: 1px solid #f0f0f0;
}

.cashier-header h2 {
  font-size: 24px;
  color: #333;
}

.countdown-banner {
  background-color: #f6f6f6;
  border-radius: 8px;
  padding: 15px;
  margin-bottom: 20px;
}

.countdown-content {
  display: flex;
  align-items: center;
}

.success-icon {
  margin-right: 15px;
  font-size: 24px;
  color: #52c41a;
}

.countdown-text {
  flex: 1;
}

.countdown-text p {
  margin: 5px 0;
  color: #666;
}

.countdown {
  color: #f5222d;
  font-weight: bold;
}

.payment-amount {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 20px;
  background-color: #fafafa;
  border-radius: 8px;
  margin-bottom: 20px;
}

.amount-label {
  font-size: 16px;
  color: #666;
}

.amount-value {
  font-size: 28px;
  font-weight: bold;
  color: #f5222d;
}

.order-detail {
  padding: 15px;
  background-color: #fafafa;
  border-radius: 8px;
  margin-bottom: 20px;
}

.detail-item {
  display: flex;
  margin-bottom: 10px;
}

.detail-item:last-child {
  margin-bottom: 0;
}

.detail-item .label {
  width: 100px;
  color: #666;
}

.detail-item .value {
  flex: 1;
  color: #333;
}

.payment-methods {
  margin-bottom: 30px;
}

.section-title {
  font-size: 18px;
  margin-bottom: 15px;
  padding-bottom: 10px;
  border-bottom: 1px solid #f0f0f0;
}

.method-list {
  border: 1px solid #e8e8e8;
  border-radius: 8px;
  overflow: hidden;
}

.method-item {
  display: flex;
  align-items: center;
  padding: 15px;
  cursor: pointer;
  transition: background-color 0.3s;
  border-bottom: 1px solid #e8e8e8;
}

.method-item:last-child {
  border-bottom: none;
}

.method-item:hover {
  background-color: #f5f5f5;
}

.method-item.active {
  background-color: #e6f7ff;
}

.method-icon {
  width: 40px;
  height: 40px;
  margin-right: 15px;
}

.method-icon img {
  width: 100%;
  height: 100%;
  object-fit: contain;
}

.method-info {
  flex: 1;
}

.method-name {
  font-size: 16px;
  font-weight: 500;
  margin-bottom: 5px;
}

.method-desc {
  font-size: 12px;
  color: #999;
}

.method-select {
  width: 24px;
  height: 24px;
  display: flex;
  align-items: center;
  justify-content: center;
  color: #1890ff;
}

.payment-action {
  text-align: center;
}

.pay-button {
  width: 100%;
  max-width: 400px;
  height: 50px;
  font-size: 18px;
  font-weight: 500;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .cashier-container {
    padding: 15px;
  }
  
  .countdown-content {
    flex-direction: column;
    align-items: flex-start;
  }
  
  .success-icon {
    margin-right: 0;
    margin-bottom: 10px;
  }
  
  .payment-amount {
    flex-direction: column;
    align-items: flex-start;
  }
  
  .amount-value {
    margin: 10px 0;
  }
}
</style>